<?php

namespace app\admin\controller\xilujob;

use app\admin\model\xilujob\Area;
use app\admin\model\xilujob\EnterpriseInfo;
use app\admin\model\xilujob\JobInfo;
use app\admin\model\xilujob\XilujobUser;
use app\common\controller\Backend;
use app\common\model\xilujob\CompanyAddress;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;
use function fast\array_get;

/**
 * 招聘职位
 *
 * @icon fa fa-circle-o
 */
class Job extends Backend
{
    protected $relationSearch = true;
    protected $searchFields = "job.job_name,enterpriseinfo.company_name";
    protected $noNeedRight = ['area','select_company','working_place','select_company_address','del_address'];
    /**
     * Job模型对象
     * @var \app\admin\model\xilujob\Job
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xilujob\Job;
        $this->view->assign("publisherTypeList", $this->model->getPublisherTypeList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("salaryTypeList", $this->model->getSalaryTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("blackList", $this->model->getBlackList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['job_category','enterpriseinfo','city'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $categoryData = \app\admin\model\xilujob\JobCategory::getCategoryData();
        $categorySearch = [];
        foreach ($categoryData as $key=>$item) {
            $categorySearch[] = [
                'id' => $key, 'name' => $item
            ];
        }
        $this->assignconfig('categorySearch', $categorySearch);
        return $this->view->fetch();
    }

    public function add() {
        if($this->request->isPost()) {
            $row = $this->request->post('row/a');
            $company_profile = \app\admin\model\xilujob\CompanyProfile::get($row['publisher_id']);
            $user = $company_profile->xilujobuser;
            $row['publisher_type'] = $user->enterprise_group_id;
            $row['user_id'] = $user->user_id;
            //工作地址
            $company_address_id = array_get($row,'company_address_id');
            if($company_address_id){
                $companyAddress = CompanyAddress::field("id as company_address_id,province_id,city_id,district_id,address_name,address,house_number,lat,lng")->where('id',$company_address_id)->find();
                $row['locations'][] = $companyAddress->toArray();
            }
            Db::startTrans();
            try {
                $ret = \app\common\model\xilujob\Job::addJob($row);
                // 设置其他属性
                $job = $ret;
                $data = ['top'=>$row['top'],'status'=>$row['status']];
                if($row['status']==\app\common\model\xilujob\Job::STATUS_ENABLED) {
                    $data['refreshtime'] = time();
                    $data['refresh_date'] = date('Y-m-d');
                }
                $job->save($data);
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }

            Db::commit();
            $this->success();
        }
        $this->assign('work_experience_options', \app\common\model\xilujob\WorkExperience::getAll());
        $this->assign('education_levels', \app\common\model\xilujob\EducationLevel::getAll());

        $this->assign('category_ids', ['','','']);
        $this->assign('benefitIds','');

        return $this->view->fetch();
    }

    public function edit($ids=null) {
        $row = $this->model->get($ids);
        if($this->request->isPost()) {
            $row = $this->request->post('row/a');
            $row['in_hurry'] = array_get($row, 'in_hurry', 0);
            //工作地址
            $company_address_id = array_get($row,'company_address_id');
            if($company_address_id){
                $companyAddress = CompanyAddress::field("id as company_address_id,province_id,city_id,district_id,address_name,address,house_number,lat,lng")->where('id',$company_address_id)->find();
                $row['locations'][] = $companyAddress->toArray();
            }
            Db::startTrans();
            try {
                $ret = \app\common\model\xilujob\Job::editJob($ids, $row);
                // 设置其他属性
                $job = $ret;
                $extra = ['top'=>$row['top'],'brand'=>array_get($row,'brand',0)];
                if(isset($row['status'])) {
                    $extra['status'] = $row['status'];
                }
                $job->save($extra);
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            Db::commit();
            $this->success();
        }

        $category = \app\admin\model\xilujob\JobCategory::get($row->job_category_id);
        $categoryIds = explode(',', substr($category->path,0, strlen($category->path)-1));//remove last comma and explode
        $this->assign('category_ids', $categoryIds);
        $this->assign('education_levels', \app\common\model\xilujob\EducationLevel::getAll());
        $this->assign('work_experience_options', \app\common\model\xilujob\WorkExperience::getAll());
        $benefits = $row->benefits;
        //halt(collection($benefits)->toArray());
        if($benefits) {
            $benefitIds = [];
            foreach ($benefits as $benefit) {
                $benefitIds[] = $benefit->id;
            }
            $this->assign('benefitIds', implode(',',$benefitIds));
        }else {
            $this->assign('benefitIds','');
        }
        //公司地址
        $companyAddress = CompanyAddress::where('company_id',$row->publisher_id)->select();
        $this->assign('companyAddress',$companyAddress);
        $res = parent::edit($ids);
        return $res;
    }

    public function select_company() {
        $q = $this->request->post('company_name');
        $query = EnterpriseInfo::alias('e')
            ->join('xilujob_user u','e.user_id=u.user_id')
            ->join('xilujob_company_profile cp','cp.id=e.company_id')
            ->where('u.enterprise_group_id','in',[2])
            ->where('cp.audit_status',1)
            ->whereNull('u.deletetime')
            ->where('company_name','<>', '');
        if($q)
            $query->where('company_name','like', "%$q%");
        $total = $query->count();

        $query = EnterpriseInfo::alias('e')
            ->join('xilujob_user u','e.user_id=u.user_id')
            ->join('xilujob_company_profile cp','cp.id=e.company_id')
            ->where('u.enterprise_group_id','in',[2])
            ->where('cp.audit_status',1)
            ->whereNull('u.deletetime')
            ->where('company_name','<>', '');
        if($q)
            $query->where('company_name','like', "%$q%");
        $query->fieldRaw('e.company_id, e.company_name, u.enterprise_group_id');
        $items = $query->select();
        $list = [];
        foreach ($items as $item) {
            $list[] = [
                'id' => $item['company_id'],
                'company_name'=>sprintf('%s - %s',$item['enterprise_group_id']==XilujobUser::GROUP_COMPANY ? '公司':'劳务店铺', $item['company_name'])
            ];
        }
        return json(['list' => $list, 'total' => $total]);
    }

    public function select_company_address() {
        $company_id = $this->request->param('company_id');
        $lists = \app\common\model\xilujob\CompanyAddress::with([
            'province'=>function($query){$query->field('id,name');},
            'city'=>function($query){$query->field('id,name');},
            'district'=>function($query){$query->field('id,name');},

        ])->where('company_id', $company_id)
            ->order('id','desc')
            ->select();
        $this->success('','',$lists);
    }

    /**
     * 读取省市区数据,联动列表
     */
    public function area()
    {
        $pid = $this->request->param('pid', 0);
        $list = Area::where('pid', $pid)->field('id as value,name')->select();
        $this->success('', null, $list);
    }


    public function audit($ids) {
        $job = $this->model->get($ids);
        if(!$job) {
            $this->error(__('no record'));
        }
        $jobInfo = JobInfo::get(['job_id'=>$job->id]);
        $company = \app\admin\model\xilujob\CompanyProfile::where('id',$job->publisher_id)->find();
        if(!$company || $company->audit_status ==0){
            $this->error("当前归属企业还未提交审核信息，不可审核");
        } else if(!$company || $company->audit_status ==2){
            $this->error("当前归属企业正在待审核中，不可审核");
        }else if(!$company || $company->audit_status ==3){
            $this->error("当前归属企业未通过审核，不可审核");
        }
        $params = array_intersect_key($this->request->post(), array_flip(['status','failed_reason']));
        if($params['status']==\app\common\model\xilujob\Job::STATUS_ENABLED) {
            // 审核通过
            $params['refreshtime'] = time();
            $params['refresh_date'] = date('Y-m-d');
            try {
                Db::startTrans();
                $ret = $job->save($params);
                $jobInfo->save(['audittime'=>time()]);
                if ($ret === false) {
                    Db::rollback();
                    $this->error($job->getError());
                }
                Db::commit();
            }catch (\Exception $e) {
                Log::error($e->getMessage()."\n".$e->getTraceAsString());
                $this->error($e->getMessage());
            }
            $job->audit_time = date('Y.m.d H:i:s');
            $this->success();
        }else if($params['status']==\app\common\model\xilujob\Job::STATUS_FAILED) {
            try {
                Db::startTrans();
                $ret = $job->save(['status'=>3]);
                $jobInfo->save(['audittime'=>time(),'failed_reason'=>$params['failed_reason']]);
                if ($ret === false) {
                    Db::rollback();
                    $this->error($job->getError());
                }
                Db::commit();
                $job->failed_reason = $params['failed_reason'];
                $job->audit_time = date('Y.m.d H:i:s');
                $this->success();
            }catch (Exception $e) {
                Log::error($e->getMessage()."\n".$e->getTraceAsString());
                $this->error($e->getMessage());
            }
        }
        $this->error(__('invalid arguments'));


    }

    /**
     * 添加地址
     * @return string
     * @throws Exception
     */
    public function working_place(){
        $this->model  = new CompanyAddress();
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del_address(){
        $id = $this->request->post('id');
        $row = $id ? \app\common\model\xilujob\CompanyAddress::where('id',$id)
            ->find() : null;
        if(!$row){
            $this->error("地址不存在");
        }
        #关联的地址
        $job = \app\common\model\xilujob\Job::alias("job")
            ->join("xilujob_job_location job_location",'job_location.job_id=job.id')
            ->where('job_location.company_address_id',$row->id)
            ->count(1);
        if($job){
            $this->error("有关联职位，不可删除");
        }
        $row->delete();
        $this->success('删除成功');
    }


}
